<template>
  <div>
    <en-table-layout
      toolbar
      pagination
      :tableData="tableData"
      :loading="loading"
      :selectionChange="selectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button type="primary" @click="handleCreateActivity">创建活动</el-button>
          <el-button type="primary" @click="handleActivity(1)">上线</el-button>
          <el-button type="primary" @click="handleActivity(2)">下线</el-button>
        </div>
        <div class="toolbar-search">          
          <en-table-search
            @search="searchEvent"
            @advancedSearch="advancedSearchEvent"
            advanced
            advancedWidth="500"
            placeholder="请输入活动名称">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="80px">
                <el-form-item label="活动时间">
                  <el-date-picker
                    v-model="advancedForm.times_range"
                    type="datetimerange"
                    value-format="timestamp"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-time="['00:00:00', '23:59:59']"
                    :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64E7 }}">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="活动状态">
                  <el-select v-model="advancedForm.status" clearable placeholder="请选择">
                    <el-option
                      v-for="item in statusOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>
      <template slot="table-columns">
        <el-table-column type="selection"/> 
        <!--活动名称-->
        <el-table-column prop="newcomer_name" width="300" label="活动名称"/>
        <!--活动时间-->
        <el-table-column label="活动时间" width="300">
          <template slot-scope="scope">
            <span>{{ scope.row.start_time | unixToDate }}</span> ～
            <span>{{ scope.row.end_time | unixToDate }}</span>
          </template>
        </el-table-column>
        <!--参团人数-->
        <el-table-column prop="limit_num" width="120" label="限选商品（个）"/>
        <!--活动状态-->
        <el-table-column prop="status" width="80" :formatter="activityStatus" label="活动状态"/>
        <!--限购数量-->
        <!-- <el-table-column prop="limit_num" width="120" label="限购数量"/> -->
        <!--是否虚拟成团-->
        <el-table-column prop="newcomer_desc" width="320" label="活动描述"/>
        <!--操作-->
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              type="success"
              @click="setActivityGoods(scope.row)">设置商品
            </el-button>
            <el-button
              type="primary"
              @click="handleUpdateActivity(scope.row)">修改
            </el-button>
            <el-button
              type="danger"
              @click="handleDeleteActivity(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column/>
      </template>
      <el-pagination
        slot="pagination"
        v-if="pageData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total">
      </el-pagination>
    </en-table-layout>
    
    <el-dialog
      :title="titleActivity"
      :visible.sync="dialogCreateActivity"
      width="560px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="activityForm"
        status-icon
        :rules="activityRules"
        label-position="right"
        ref="activityForm"
        label-width="120px"
        class="demo-ruleForm">
        <el-form-item  label="活动名称：" prop="newcomer_name">
          <el-input
            v-model="activityForm.newcomer_name"
            @change="activityForm.newcomer_name  = activityForm.newcomer_name.trim()"
            placeholder="不超过25个字符"
            maxLength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动时间：" prop="take_effect_time">
          <el-date-picker
            v-model="activityForm.take_effect_time"
            type="datetimerange"
            value-format="timestamp"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64E7 }}">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="限选商品：" prop="limit_num">
          <el-input v-model="activityForm.limit_num" @change="activityForm.limit_num = activityForm.limit_num.trim()">
            <template slot="append">个</template>
          </el-input>
        </el-form-item>
        <el-form-item label="活动描述：" prop="newcomer_desc">
          <!-- <UE ref="UE" :defaultMsg="activityForm.description"></UE> -->
          <el-input type="textarea" autosize v-model="activityForm.newcomer_desc"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSaveActivity('activityForm')">保存</el-button>
          <el-button @click="handleCancelSaveActivity('activityForm')">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    <el-dialog
      title="设置商品"
      :visible.sync="dialogSetGoods"
      width="1000px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <en-table-layout
        toolbar
        pagination
        class="addGoodsDialog"
        :tableData="activityData.goods_data"
        :loading="loading"
        :selectionChange="selectionChange">
        <div slot="toolbar" class="inner-toolbar">
          <div class="toolbar-btns">
            <el-button type="primary" @click="selectgoodslist" >添加商品</el-button>
          </div>
        </div>
        <template slot="table-columns" class="setGoods">
          <el-table-column type="index" label="序号"/>
          <el-table-column label="商品ID" prop="sku_id"/>
          <el-table-column label="商品名称" prop="goods_name"/>
          <el-table-column label="店铺价格" prop="mktprice"/>
          <el-table-column label="专享价格" width="100" prop="sales_price">
            <template slot="header" slot-scope="scope">
              <p><span style="color:red;">*</span>专享价格</p>
            </template>
            <template slot-scope="scope">
              <el-input placeholder="输入专享价格" v-model="scope.row.sales_price" clearable>
                <!-- <template slot="prepend">¥</template> -->
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="活动数量" width="100">
            <template slot="header" prop="sold_quantity" slot-scope="scope">
              <p><span style="color:red;">*</span>活动数量</p>
            </template>
            <template slot-scope="scope">
              <!-- 校验数量 -->
              <el-input placeholder="输入活动数量" v-model="scope.row.sold_quantity" clearable>
                <template slot="prepend"></template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="限购数量" width="100">
            <template slot-scope="scope">
              <!-- 校验数量 -->
              <el-input placeholder="输入限购数量" v-model="scope.row.limit_num" clearable>
                <template slot="prepend"></template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="danger" @click="canceljoin(scope)">删除 </el-button>
            </template>
          </el-table-column>
        </template>
      </en-table-layout>
      <div style="text-align: center;">
        <el-button type="primary" @click="handleSaveAssembleGoods">保存设置</el-button>
      </div>
      <en-goods-sku-picker
        type="seller"
        goods-type="NORMAL"
        :show="showDialog"
        :sku="true"
        :api="goodsApi"
        :multipleApi="multipleApi"
        :defaultData="skuIds"
        :categoryApi="categoryApi"
        :limit="maxsize"
        @confirm="refreshFunc"
        @close="showDialog = false"/>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import * as API_activity from '@/api/activity'
  import { GoodsSkuPicker } from '@/components'
  import { cloneObj } from '@/utils/index'

  export default {
    name: 'newComerActivity',
    components: {
      [GoodsSkuPicker.name]: GoodsSkuPicker
    },
    computed: {
      ...mapGetters([
        'shopInfo'
      ])
    },
    data() {
      return {
        /** 列表loading状态 */
        loading: false,
        dialogSetGoods: false,
        dialogCreateActivity: false,
        titleActivity: '',
        curNewComerID: null,

        advancedForm: {
          times_range: [],
          status: null
        },
        statusOptions: [
          { value: ' ', label: '全部' },
          { value: 1, label: '待上线' },
          { value: 2, label: '已上线' },
          { value: 3, label: '已下线' }
        ],
        activityForm: {
          newcomer_name: null,
          take_effect_time: null,
          limit_num: null,
          newcomer_desc: null
        },

        activityRules: {
          newcomer_name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' }
          ],
          take_effect_time: [
            { required: true, message: '请输入活动时间', trigger: 'blur' }
          ],
          limit_num: [
            { required: true, message: '请输入限选数量', trigger: 'blur' }
          ],
          newcomer_desc: [
            { required: false, message: '请输入活动描述', trigger: 'blur' }
          ]
        },
        /** 列表参数 */
        params: {
          page_no: 1,
          page_size: 10
        },

        /** 列表数据*/
        tableData: [],

        multipleSelection: null,

        /** 活动信息*/
        activityData: {
          goods_data: []
        },

        /** 商品skuIds */
        skuIds: [],

        /** 选中的商品sku_id */
        selectionids: [],

        /** 当前操作的表格序列*/
        _order: 0,

        /** 商品选择器最大长度*/
        maxsize: 0,

        /** 商品选择器列表api*/
        goodsApi: 'seller/goods/skus?market_enable=1&is_auth=1',

        multipleApi: 'seller/goods/skus/@ids/details',

        /** 商城分类api */
        categoryApi: 'seller/goods/category/0/children',

        /** 显示/隐藏商品选择器 */
        showDialog: false,

        /** 列表分页数据 */
        pageData: null
      }
    },
    mounted() {
      this.GET_NewComerActivityList()
    },
    methods: {
      /** 获取选中项*/
      selectionChange(val) {
        this.multipleSelection = val;
      },
      /** 秒杀状态显示 */
      activityStatus({ status }) {
        switch (status) {
          case 1: return '待上线'
          case 2: return '已上线'
          case 3: return '已下线'
        }
      },

      /** 搜索事件触发 */
      searchEvent(data) {
        this.params = {
          ...this.params,
          newcomer_name: data
        }
        this.GET_NewComerActivityList()
      },
      // 高级搜索
      advancedSearchEvent() {
        let _searchForm = JSON.parse(JSON.stringify(this.advancedForm));
        for (const _key in _searchForm) {
          if (_searchForm[_key] === '') { // 当条件值为''时去除条件
            delete _searchForm[_key];
          }
        }
        if (_searchForm.times_range.length > 0) {
          _searchForm.start_time = _searchForm.times_range[0] / 1000;
          _searchForm.end_time = _searchForm.times_range[1] / 1000;
        }
        delete _searchForm.times_range
        this.params = {
          ...this.params,
          ..._searchForm
        }
        this.params.page_no = 1;
        this.GET_NewComerActivityList();
      },

      /** 分页大小发生改变 */
      handlePageSizeChange(size) {
        this.params.page_size = size
        this.GET_NewComerActivityList()
      },

      /** 分页页数发生改变 */
      handlePageCurrentChange(page) {
        this.params.page_no = page
        this.GET_NewComerActivityList()
      },

      /** 获取活动列表 */
      GET_NewComerActivityList() {
        this.loading = true
        API_activity.getNewComerList(this.params).then(response => {
          this.loading = false
          this.tableData = response.data
          this.pageData = {
            page_no: response.page_no,
            page_size: response.page_size,
            data_total: response.data_total
          }
        }).catch((err) => {
          this.$message.error(err)
          this.loading = false
        })
      },

      /** 添加或修改活动 */
      handleSaveActivity(activityForm) {
        this.$refs[activityForm].validate((valid) => {
          if (valid) {
            this.loading = true
            this.activityForm.start_time = this.activityForm.take_effect_time[0] / 1000
            this.activityForm.end_time = this.activityForm.take_effect_time[1] / 1000
            delete this.activityForm.take_effect_time
            let params = {
              ...this.params,
              ...this.activityForm
            }
            API_activity.addOrUpdateActivity(params).then(response => {
              this.loading = false
              this.dialogCreateActivity = false
              this.$refs[activityForm].resetFields()
              this.GET_NewComerActivityList()
            }).catch((err) => {
              this.$message.error(err)
              this.loading = false
            })
          }
        })
      },

      handleCancelSaveActivity(activityForm) {
        this.$refs[activityForm].resetFields()
        this.dialogCreateActivity = false
      },

      /** 新增/编辑活动 */
      handleCreateActivity(row) {
        this.titleActivity = '创建活动'
        this.dialogType = 'add'
        this.dialogCreateActivity = true
      },

      /** 修改活动 */
      handleUpdateActivity(row) {
        this.titleActivity = '修改活动'
        this.dialogType = 'change'
        this.$nextTick(() => {
          this.activityForm = {
            newcomer_id: row.newcomer_id,
            newcomer_name: row.newcomer_name,
            take_effect_time: [row.start_time*1000, row.end_time*1000],
            limit_num: row.limit_num,
            newcomer_desc: row.newcomer_desc
          }
        })
        this.dialogCreateActivity = true
      },

      /** 获取新人购商品列表 */
      GET_NewcomerGoodsList(newcomer_id) {
        API_activity.getNewcomerGoodsList(newcomer_id).then(response => {
          this.skuIds = []
          response.forEach(item => {
            this.skuIds.push(item.sku_id);
          })
          response.forEach((item) => {
            item.mktprice = item.seller_price
          })
          this.activityData.goods_data = response
        }).catch((err) => {
          this.$message.error(err)
          this.loading = false
        })
      },
      
      /** 设置活动商品 */
      setActivityGoods(row) {
        this.dialogSetGoods = true
        this.curNewComerID = row.newcomer_id
        this.GET_NewcomerGoodsList(this.curNewComerID);
      },
      
      /** 上下线活动 */
      handleActivity(type) {
        if (type === 2) {
          let params = {
            newcomer_id: this.multipleSelection[0].newcomer_id,
            status: 3
          }
          this.$confirm('确认下线当前活动？', '确认信息', { type: 'warning' }).then(() => {
            API_activity.onOffLine(params).then(() => {
              this.$message.success('下线成功！')
              this.GET_NewComerActivityList()
            }).catch((err) => {
              this.$message.error(err)
            })
          }).catch(() => {})
        } else {
          let params = {
            newcomer_id: this.multipleSelection[0].newcomer_id,
            status: 2
          }
          API_activity.onOffLine(params).then(() => {
            this.$message.success('上线成功！')
            this.GET_NewComerActivityList()
          }).catch((err) => {
            this.$message.error(err)
          })
        }
      },
      
      /** 删除活动 */
      handleDeleteActivity(row) {
        this.$confirm('确认删除当前活动？', '确认信息', { type: 'warning' }).then(() => {
          API_activity.delNewComerActivity(row.newcomer_id).then(() => {
            this.$message.success('删除成功！')
            this.GET_NewComerActivityList()
          })
        }).catch(() => {})
      },

      /** 删除已选中的商品*/
      handleDelgoods($index, row) {
        this.activityData.goods_data.forEach((elem, index) => {
          if (row.sku_id === elem.sku_id) {
            this.activityData.goods_data.splice(index, 1)
          }
        })
      },

      /**  显示商品选择器*/
      selectgoodslist($index) {
        this.showDialog = true
        this._order = $index
      },

      /** 获取规格列表 */
      getSkuList(val) {
        const _val = typeof val === 'string' ? JSON.parse(val) : val
        if (_val) {
          const _specs = _val.map(key => {
            return {
              name: key.spec_name,
              value: key.spec_value
            }
          })
          return _specs
        }
        return []
      },

      /** 保存商品选择器选择的商品 */
      refreshFunc(val) {
        const _val = val
        this.activityData.goods_data.forEach(key => {
          _val.forEach(item => {
            if (item.sku_id === key.sku_id) {
              item.sales_price = key.sales_price
              item.price = key.price
              item.sold_quantity = key.sold_quantity
              item.limit_num = key.limit_num
            }
          })
        })
        this.activityData.goods_data = cloneObj(_val)
        this.skuIds = this.activityData.goods_data.map(key => key.sku_id)
      },

      /**  取消参加 */
      canceljoin(scope) {
        this.activityData.goods_data.forEach((elem, index) => {
          if (elem.sku_id === scope.row.sku_id) {
            this.activityData.goods_data.splice(index, 1)
          }
        })
        this.skuIds = this.activityData.goods_data.map(key => key.sku_id)
      },

      /** 保存秒杀活动商品详情信息 */
      handleSaveAssembleGoods() {
        if (!this.activityData.goods_data || !Array.isArray(this.activityData.goods_data) || !this.activityData.goods_data.length) {
          this.$message.error('请选择要参加秒杀的商品')
          return
        } else if (this.activityData.goods_data.some(key => { return !key.sales_price && parseInt(key.sales_price) !== 0 })) {
          this.$message.error('请填写新人专享价格')
          return
        } if (this.activityData.goods_data.some(key => { return !key.sold_quantity && parseInt(key.sold_quantity) !== 0 })) {
          this.$message.error('请填写商品活动数量')
          return
        }
        const _params = this.activityData.goods_data.map(key => {
          return {
            cost: key.cost,
            goods_id: key.goods_id,
            goods_name: key.goods_name,
            limit_num: key.limit_num,
            newcomer_id: this.curNewComerID,
            sales_price: key.sales_price,
            seller_price: key.mktprice,
            sku_id: key.sku_id,
            sold_quantity: key.sold_quantity
          }
        })
        API_activity.addNewcomerGoods(_params).then((res) => {
          this.$message.success(res.message)
          this.dialogSetGoods = false
          this.$router.push({ path: '/promotions/newComerActivity' })
          this.$store.state.tagsView.cachedViews = this.$store.state.tagsView.cachedViews.filter(tab => tab !== 'newComerActivity')
          this.$store.state.tagsView.visitedViews = this.$store.state.tagsView.visitedViews.filter(tab => tab.name !== 'newComerActivity')
        }).catch((err) => {
          this.$message.error(err)
        })
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  >>> div.toolbar {
    height: 70px;
    padding: 15px;
  }
  /deep/ input::-webkit-input-placeholder{
    font-size: 12px;
  }
  .addGoodsDialog /deep/ .el-input--small .el-input__inner{
    padding: 0;
    text-align: center;
  }
  .addGoodsDialog /deep/ .el-table__body-wrapper{
    overflow: auto;
    overflow-x: hidden;
    position: relative;
    max-height: 400px;
  }
</style>
